#include "Yoshi.h"
 
Yoshi::Yoshi() {
    CurrentFrame    = 0;
    MaxFrames       = 8;
    FrameInc        = 1;
 
    anim_FrameRate  = 100; //Milliseconds
    anim_OldTime    = 0;

	animMoveRatio   = 6;

	move_FrameRate  = anim_FrameRate / animMoveRatio;  //Milliseconds
    move_OldTime    = 0;

	Yoshi_x_pos     = 0;
	Yoshi_y_pos     = 0;
	direction       = DIR_STOP;

}

void Yoshi::Init(int x_pos,int y_pos) {

	Yoshi_x_pos = x_pos;
	Yoshi_y_pos = y_pos;

	if((Yoshi_bmp = CSurface::OnLoad("../SDL_Tutorial/Images/yoshi.bmp")) == NULL) {
        return;
    }
	// Define the transparent color
	SDL_SetColorKey( Yoshi_bmp, SDL_SRCCOLORKEY, SDL_MapRGB(Yoshi_bmp->format, 255, 0, 255) );

	direction = DIR_LEFT;
}
 
void Yoshi::OnRender(SDL_Surface *surface) {

	int spriteSetY = (direction == DIR_RIGHT)? 64 : 0;

	CSurface::OnDraw(surface, Yoshi_bmp, Yoshi_x_pos, Yoshi_y_pos, spriteSetY, CurrentFrame * 64, 64, 64);
}

void Yoshi::OnLoop() {

	const long currTime = (long)SDL_GetTicks();

	// Animation
	if(anim_OldTime + anim_FrameRate < currTime ) {

		anim_OldTime = currTime;

		CurrentFrame += FrameInc;


		if(CurrentFrame >= MaxFrames) {
			CurrentFrame = 0;
		}
	}

	// Moving
	if(move_OldTime + move_FrameRate < currTime) {
		move_OldTime = currTime;

		if( direction == DIR_RIGHT ) {
			Yoshi_x_pos += 1;
			if( Yoshi_x_pos > 650 ) Yoshi_x_pos = (-200) +int(180*rand()/(RAND_MAX + 1.0));
		}
		if( direction == DIR_LEFT ) {
			Yoshi_x_pos -= 1;
			if( Yoshi_x_pos < -50 ) Yoshi_x_pos = (650) +int(100*rand()/(RAND_MAX + 1.0));
		}

	}
}
 
void Yoshi::SetFrameRate(int Rate) {
    anim_FrameRate = Rate;
	move_FrameRate  = anim_FrameRate / animMoveRatio;
}

void Yoshi::SetDirection(int dir) {

	direction = dir;
}
 
void Yoshi::SetCurrentFrame(int Frame) {
    if(Frame < 0 || Frame >= MaxFrames) return;
 
    CurrentFrame = Frame;
}
 
